package com.wen.qqrobot.strategy;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
 * Created by wenwen on 2016/10/5.
 * version 1.0
 */
public class YoudaoTranslateService {
    /**
     * 发起http请求获取返回结果
     *
     * @param requestUrl 请求地址
     * @return
     */
    public static String httpRequest(String requestUrl) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            // 设置是否向httpUrlConn输出
            httpUrlConn.setDoOutput(false);
            // 设置是否向httpUrlConn读入，默认是ture
            httpUrlConn.setDoInput(true);
            // Post 请求不能使用缓存,get可以
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod("GET");
            // 链接
            httpUrlConn.connect();

            //将返回的书人流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return buffer.toString();
    }

    /**
     * utf编码
     *
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 翻译（中->英 英->中 ）
     *
     * @param source
     * @return
     */
    public static String translate(String source) {
        String dst = "";

        //组装查询地址
        String requestUrl = "http://fanyi.youdao.com/openapi.do?keyfrom=508studio&key=1986591469&type=data&doctype=json&version=1.1&q={keyWord}";
        //对参数的值进行urlEncode utf-8编码
        requestUrl = requestUrl.replace("{keyWord}", urlEncodeUTF8(source));

        //查询并解析结果
        try {
            // 查询并返回结果
            String json = httpRequest(requestUrl);
            //System.out.println(json);
            /*// 以下是通过gson工具将json转换为TranslateResult对象
            TranslateResult translateResult = new Gson().fromJson(json, TranslateResult.class);
    		//取出translateResult中的译文
    		dst = translateResult.getTranslation().get(0).getBytes("utf-8").toString()+translateResult.getQuery();*/
    		/*
    		 * 普通的json解析
    		 */
            JSONObject jsonObject = JSONObject.fromObject(json);
            // 获得翻译数组结果
            JSONArray translation = jsonObject.getJSONArray("translation");
            // 获得基本词义
            JSONObject basic = jsonObject.getJSONObject("basic");
            JSONArray explains = null;
            // 因为句子和单词的翻译是不同！
            if (basic.containsKey("explains")) {
                explains = basic.getJSONArray("explains");
            }
            // 落得网络词义
            JSONArray web = null;
            if (basic.containsKey("web"))
                web = jsonObject.getJSONArray("web");

            //下面是输出格式
    		/*System.out.print(source+"\n");
    		System.out.print("---有道翻译---"+"\n");*/
            dst = dst + source + "\n" + "---有道翻译---" + "\n";
            int transNum = translation.size();
            for (int i = 0; i < transNum; i++) {
                //System.out.print(translation.get(i)+"\n");
                dst = dst + translation.get(i) + "\n";
            }
            //System.out.print("---基本翻译---\n");
            if (basic.containsKey("explains")) {
                dst = dst + "---基本翻译---\n";
                int exNum = explains.size();
                for (int i = 0; i < exNum; i++) {
                    //System.out.print(explains.get(i)+"\n");
                    dst += explains.get(i) + "\n";
                }
                //System.out.println("---网络扩展---\n");
            }
            if (basic.containsKey("web")) {
                dst += "---网络扩展---\n";
                int webNum = web.size();
                for (int i = 0; i < webNum; i++) {
                    JSONObject webObject = (JSONObject) web.get(i);
                    String webKey = webObject.getString("key");
                    //System.out.print(webKey+"\n");
                    dst += webKey + "\n";
                    JSONArray value = webObject.getJSONArray("value");
                    int valueNum = value.size();
                    for (int j = 0; j < valueNum; j++) {
                        //System.out.print(value.get(j)+"\n");
                        dst += value.get(j) + "\n";
                    }
                    //System.out.println("-----------\n");
                    dst += "-----------\n";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == dst)
            dst = "翻译系统异常，请稍后尝试！";
        return dst;
    }

    /**
     * 英汉翻译使用指南
     *
     * @return
     */
    public static String getTranslateUsage() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("英汉使用指南").append("\n\n");
        buffer.append("英汉翻译为用户提供专业的中英语言翻译服务，目前支持以下翻译方向：").append("\n");
        buffer.append("    中 -> 英").append("\n");
        buffer.append("    英 -> 中").append("\n");
        buffer.append("使用示例：").append("\n");
        buffer.append("    翻译我是中国人").append("\n");
        buffer.append("    翻译dream").append("\n");
        //buffer.append("回复“?”显示主菜单");
        return buffer.toString();
    }

    public static void main(String[] args) {
        System.out.println(translate("running man"));
    }
}
